<template>
  <div class="market">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchValue"
        placeholder="搜索商品"
        shape="round"
        background="#4fc08d"
      />
      <van-button 
        size="small" 
        type="primary" 
        round 
        @click="handleSearch"
        style="margin-left: -70px; position: relative; z-index: 1;width: 60px; height: 32px; margin-top: 10px;"
      >搜索</van-button>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 商品分类 -->
      <div class="categories">
        <van-grid :column-num="4">
          <van-grid-item @click="handleCategoryClick(item)" v-for="item in categories" :key="item.id" :icon="item.icon" :text="item.text" />
        </van-grid>
      </div>

      <!-- 商品列表 -->
      <div class="products">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div class="product-grid">
              <van-card
                v-for="item in productList"
                :key="item.id"
                :price="item.price"
                :title="item.name"
                :desc="item.description"
                :thumb="item.url"
              >
            <template #tags>
              <van-tag plain type="danger">{{ item.tag }}</van-tag>
            </template>
            <template #footer>
              <van-button size="small" type="primary" @click="onAddToCart(item)">加入购物车</van-button>
            </template>
          </van-card>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <tab-bar />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import TabBar from '@/components/TabBar.vue'
import request from '@/utils/request'
import {searchStore} from '@/store/searchStore'
import { useRouter } from 'vue-router'

const router = useRouter()
// 搜索相关
const searchValue = ref('')
const store = searchStore()

// 分类数据
const categories = [
  { id: 1, text: '蔬菜', icon: 'flower-o' },
  { id: 2, text: '水果', icon: 'gift-o' },
  { id: 4, text: '种子', icon: 'diamond-o' },
  { id: 8, text: '更多', icon: 'apps-o' }
]

// 商品列表相关
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const productList = ref(()=>[])

const handleCategoryClick = (item) => {
  if(item.text === '更多'){
    router.push('/search')
  }
  store.setSearchQuery(item.text)
  router.push('/search')
  
}
// 搜索处理函数
const handleSearch = () => {
  store.setSearchQuery(searchValue.value)
  if (!searchValue.value.trim()) {
    startFn();
    return
  }
  
  // 存储到Pinia store
  
  // 跳转到搜索页面
  router.push('/search')

  
}

// 下拉刷新
const onRefresh = () => {
  finished.value = false
  setTimeout(() => {
    productList.value = []
    refreshing.value = false
    onLoad()
  }, 1000)
}
function startFn(){
  request.get('/products')
  .then(res => {
    productList.value = res
    productList.value.forEach(item => {
      item.url = `http://8.137.113.18:8889${item.url}`
    })
  })
  .catch(err => {
    console.log(err)
  })
}
startFn();
// 加载更多
const onLoad = () => {
  // 异步更新数据
  setTimeout(() => {
    for (let i = 0; i < 10; i++) {
      const item = {
        id: productList.value.length + 1,
        title: `商品${productList.value.length + 1}`,
        price: (Math.random() * 100).toFixed(2),
        thumb: 'https://img01.yzcdn.cn/vant/ipad.jpeg',
        tag: Math.random() > 0.5 ? '特价' : '热卖',
        isHot: Math.random() > 0.5,
        isNew: Math.random() > 0.5
      }
      productList.value.push(item)
    }
    loading.value = false

    // 数据全部加载完成
    if (productList.value.length >= 40) {
      finished.value = true
    }
  }, 1000)
}

// 添加到购物车
const onAddToCart = (item) => {
  alert('添加成功')
}
</script>

<style lang="scss" scoped>
.market {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.search-bar {
  position: fixed;
  display: flex;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
:deep(.van-search){
  width: 100%
}
:deep(.van-search__content){
  margin-right: 60px;
}

.content {
  flex: 1;
  overflow-y: auto;
  margin-top: 54px; // 顶部搜索栏的高度
  padding-bottom: 50px; // 底部导航的高度
}

.categories {
  background-color: #fff;
  margin-bottom: 8px;
}

.products {
  .product-grid {
    padding: 8px;
    
    .van-card {
      margin-bottom: 8px;
      background-color: #fff;
    }
  }
}
</style> 